<template>
  <component is="a-modal" v-model:visible="visible" :width="800" :title="title" :mask-closable="false"
    :ok-loading="loading" @cancel="close" @before-ok="submit">
    <div >
      <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
        <div v-if="mode == 'tw_ziti'">
          <a-form-item label="自提状态" field="state">
            <sa-radio v-model="formData.state" :data="STATE"></sa-radio>
          </a-form-item>
          <!-- 已自提 -->
          <div v-if="formData.state == 1">
            <div v-if="totalCount > 0">
                <a-form-item label="先扫描溯源码再自提" field="sourceCode">
                  <a-input style="width: 60%;" :disabled="Count == totalCount" @keydown.enter="checkCodes()"
                    placeholder="请扫描或输入溯源码(12位)" :max-length="12" :allow-clear="true" v-model="formData.sourceCode"></a-input>
                </a-form-item>
                <div style="margin-left: 50px;margin-bottom: 5px;">1、使用得力扫码枪如在 WIN11 系统，需预设美式键盘。</div>
                <div style="margin-left: 50px;margin-bottom: 5px;">2、扫码时，<span
                    style="color:red">请先将鼠标聚焦至输入框内</span>再使用扫码枪扫码。
                </div>
                <div style="margin-left: 50px;margin-bottom: 5px;">3、手动输入时请<span style="color:red">按下 Enter 键提交。</span>
                </div>
                <div style="margin-left: 50px;margin-bottom: 5px;">4、建议使用 Firefox 浏览器版本 v117.0</div>
                <div style="margin-left: 50px;margin-top: 30px;margin-bottom: 20px;" v-if="totalCount > 0">
                  共需绑定 {{ Count }} / {{ totalCount }} 条
                </div>
                <div style="margin-left: 20px;" v-if="totalCount > 1">
                  <span>已扫描溯源码列表:</span>
                  <div v-for="(itm, idx) of sourceCodeList" :key="idx">
                    <div>{{ '第' + (idx + 1) + '条' }} : {{ itm }}</div>
                  </div>
                </div>
              </div>


            <div v-if="isAllChecked">
              <a-form-item label="发货时间" field="shipping_time">
                  <a-date-picker show-time style="width: 60%;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="请选择"
              v-model="searchForm.shipping_time" />
              </a-form-item>
              <a-form-item label="备注" field="note">
                <a-input style="width: 60%;" placeholder="请输入" :allow-clear="true" v-model="formData.note"></a-input>
              </a-form-item>
            </div>
          </div>
          <!-- 物流配送 -->
          <div v-else>
            <a-form-item label="城市" field="city_id">
              <sa-select style="width: 60%;" v-model="formData.city_id" :data="paramsData.citys"
                :fieldNames="{ value: 'id', label: 'name' }"></sa-select>
            </a-form-item>
            <a-form-item label="详细地址" field="address">
              <a-input style="width: 60%;" placeholder="请输入" :allow-clear="true" v-model="formData.address"></a-input>
            </a-form-item>
            <a-form-item label="姓名" field="name">
              <a-input style="width: 60%;" placeholder="请输入" :allow-clear="true" v-model="formData.name"></a-input>
            </a-form-item>
            <a-form-item label="手机号" field="mobile">
              <a-input style="width: 60%;" placeholder="请输入" :allow-clear="true" v-model="formData.mobile"></a-input>
            </a-form-item>
            <a-form-item label="备注" field="note">
              <a-input style="width: 60%;" placeholder="请输入" :allow-clear="true" v-model="formData.note"></a-input>
            </a-form-item>
          </div>
        </div>
        <div v-else>
          <a-form-item label="快递公司" field="company_id">
            <sa-select style="width: 60%;" v-model="formData.company_id" :data="paramsData.company"
              :fieldNames="{ value: 'id', label: 'name' }"></sa-select>
          </a-form-item>
          <a-form-item label="快递单号" field="code">
            <a-input style="width: 60%;" placeholder="请输入" :allow-clear="true" v-model="formData.code"></a-input>
          </a-form-item>
          <a-form-item label="快递发货时间" field="shipping_time">
            <a-date-picker show-time style="width: 60%;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="请选择"
              v-model="formData.shipping_time" />
          </a-form-item>
        </div>

      </a-form>
    </div>
  </component>
</template>
<script setup>
import { onMounted, ref, reactive, computed, watch } from 'vue'
import AsApi from '@/api/system/afterSale'
import SaRadio from '@cps/sa-radio/index.vue'
import SaSelect from '@cps/sa-select/index.vue'
import { Message } from '@arco-design/web-vue'
import { throttle } from 'lodash';
import tool from '@/utils/tool'
const emit = defineEmits(["success"]);
const visible = ref(false);
const Count = ref(0)
const formRef = ref(null);
const title = ref('')
const mode = ref('')
const loading = ref(false);
const STATE = ref([
  { value: 1, title: '已自提' },
  { value: 2, title: '转物流配送' }
])
const totalCount = ref(0)
const sourceCodeList = ref([])
const formData = reactive({
  state: 1,
  id: '',
  code: '',
  order_id: '',
  shipping_time: '',
  company_id: '',
  note: '',
  city_id: '',
  address: '',
  name: '',
  mobile: '',
  codes: '',
  sourceCode:''
})
const rules = ref({
  state: [{ required: true, message: "请选择" }],
  company_id: [{ required: true, message: "请选择" }],
  shipping_time: [{ required: true, message: "请选择" }],
  city_id: [{ required: true, message: "请选择" }],
  address: [{ required: true, message: "请输入" }],
  name: [{ required: true, message: "请输入" }],
  mobile: [{ required: true, message: "请输入" }],
  code:[{ required: true, message: "请输入" }],
  sourceCode: [{ required: true, message: "请输入" }, {
    validator: (value, cb) => {
      const numberOnlyRegex = /^\d{12}$/;

      if (!value) {
        cb('请输入')
      } else if (!numberOnlyRegex.test(value)) {
        cb('请输入12位数字')
      } else {
        cb(); // 校驗通过
      }
    },
    trigger: "blur"
  }],

});
const paramsData = ref({})
const isAllChecked = ref(false)
const getParams = async () => {
  const { data } = await AsApi.delievry_output_order_params(formData.id)
  paramsData.value = { ...data }
  totalCount.value = paramsData.value?.info?.goodCount
  if (totalCount.value == 0) {
    isAllChecked.value = true
  }
}
const checkCodes = async () => {
  console.log('111', formData.sourceCode);
  if (Count.value < totalCount.value) {
    if (!sourceCodeList.value.includes(formData.code.trim())) {
      const params = { code: formData.sourceCode, order_id: formData.order_id }
      const { data } = await AsApi.checkCode(params)
      Count.value++
      sourceCodeList.value.push(formData.sourceCode.trim())
    } else {
      Message.error('此溯源码已扫描')
    }
  } else if (Count.value == totalCount.value) {
    isAllChecked.value = true
  }
}
const submit = throttle(async (done) => {
  const validate = await formRef.value?.validate();
  if (!validate) {
    loading.value = true;
    try {
      let result = {};
      if (formData.state == 1) {
        // 添加数据
        let data = {//自提
          id: formData.id,
          state: formData.state,
          shipping_time: formData.shipping_time,
          note: formData.note,
          codes: sourceCodeList.value.join(',')
        }
        result = await AsApi.delievry_output_order(data);
      } else {
        let data={}
        if(mode.value=='tw_lidao'){//其他倉
          data = {
          id: formData.id,
          state: formData.state,
          company_id: formData.company_id,
          code: formData.code,
          shipping_time: formData.shipping_time,
        }
        }else{//離島
           data = {
          id: formData.id,
          state: formData.state,
          city_id: formData.city_id,
          address: formData.address,
          name: formData.name,
          mobile: formData.mobile,
          note: formData.note
        }
        }
        
        result = await AsApi.delievry_output_order(data);
      }
      if (result.code === 200) {
        Message.success("操作成功");
        emit("success");
        done(true);
      }
      // 防止连续点击提交
      setTimeout(() => {
        loading.value = false;
      }, 500);
    } catch {
      loading.value = false;
    }
  }
  done(false);
}, 100);
const open = async (type, data) => {
  console.log('1111', data);
  formData.id = data.id;
  formData.order_id = data.id;
  sourceCodeList.value = []
  formRef.value.resetFields();
  isAllChecked.value = false
  mode.value = type
  Count.value = 0
  totalCount.value = 0
  visible.value = true;
  title.value = '发货'
  await getParams()
}
defineExpose({ open });
</script>

<!-- 000999888777 -->